<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--区域数据-->
      <!-- <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input v-model="deptName" placeholder="请输入区域名称" clearable prefix-icon="Search"
                  style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
               <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false"
                  :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all
                  @node-click="handleNodeClick" />
            </div>
         </el-col> -->
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户信息搜索" label-width="100">
            <el-input placeholder="请输入内容" v-model="usermsg" class="input-with-select" clearable>
              <template #prepend>
                <el-select v-model="select" slot="prepend" placeholder="请选择" style="width: 100px"
                  @change="usermsgchange">
                  <el-option v-for="item in usermsgList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="持有金豆大于" prop="jindouAmount" label-width="100">
            <el-input v-model="queryParams.jindouAmount" placeholder="请输入持有金豆大于" type="number" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="持有功德金大于" prop="gongdejinAmount" label-width="120">
            <el-input v-model="queryParams.gongdejinAmount" placeholder="请输入持有功德金大于" type="number" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="等级" prop="status">
            <el-select v-model="queryParams.levelId" placeholder="用户等级" clearable>
              <el-option v-for="dict in levelsList" :key="dict.levelId" :label="dict.levelName" :value="dict.levelId" />
            </el-select>
          </el-form-item>

          <el-form-item label="角色" prop="status">
            <el-select v-model="queryParams.roleId" placeholder="用户角色" clearable>
              <el-option v-for="dict in roleList" :key="dict.roleId" :label="dict.roleName" :value="dict.roleId" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="类型" prop="status">
            <el-select v-model="queryParams.userType" placeholder="用户类型" clearable>
              <el-option v-for="dict in userTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:user:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Upload" @click="handleImport"
              v-hasPermi="['system:user:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleShangdou"
              v-hasPermi="['system:user:export']">熵豆达人余额导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
          <el-table-column label="用户类型" align="center" key="userType" prop="userType">
            <template #default="scope">
              {{ scope.row.userType == "01" ? "会员用户" : "管理员" }}
            </template>
          </el-table-column>
          <el-table-column label="用户信息" align="center" key="userId">
            <template #default="scope">
              <div>用户账号：{{ scope.row.userName }}</div>
              <div>用户昵称：{{ scope.row.nickName }}</div>
              <div>手机号码：{{ scope.row.phonenumber }}</div>
            </template>
          </el-table-column>
          <el-table-column label="用户等级" align="center" key="userId">
            <template #default="scope">
              <div v-for="(item, index) in scope.row.levels" :key="item.id">
                <p>
                  用户等级{{ scope.row.levels.length > 1 ? index + 1 : "" }}：{{
                    item.levelName
                  }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户角色" align="center" key="userId">
            <template #default="scope">
              <div v-for="(item, index) in scope.row.roles" :key="item.id">
                <p>
                  用户角色{{ scope.row.roles.length > 1 ? index + 1 : "" }}：{{
                    item.roleName
                  }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户余额" align="center" key="userId">
            <template #default="scope">
              <div v-for="item in scope.row.userRichList" :key="item.id">
                <div>
                  <span>{{ item.moneyName }}</span>
                  <span style="margin-left: 10px">{{ item.amount }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="上级用户信息" align="center" key="userId">
            <template #default="scope">
              <div v-if="scope.row.superiorInfo">
                <p>用户名:{{ scope.row.superiorInfo?.userName }}</p>
                <p>手机:{{ scope.row.superiorInfo?.phonenumber }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="兑换次数" align="center" prop="exchangeNum" />
          <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
            <template #default="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-tooltip content="修改" placement="top" v-if="scope.row.userId === 1">
                  <el-button link type="primary" @click="handleGoincome(scope.row)"
                    v-hasPermi="['system:user:edit']">收支明细</el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top" v-if="scope.row.userId === 1">
                  <el-button link type="primary" @click="handleColl(scope.row)"
                    v-hasPermi="['system:user:edit']">修改收款信息</el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:user:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['system:user:remove']"></el-button>
                </el-tooltip>
                <el-dropdown trigger="click" v-if="scope.row.userId !== 1">
                  <span type="primary" size="small">
                    更多操作
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)"
                          v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)"
                          v-hasPermi="['system:user:edit']">分配角色</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="Coin" @click="handleUserCoin(scope.row)"
                          v-hasPermi="['system:user:coin']">货币充值</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="Edit" @click="updateUserSuper(scope.row)"
                          v-hasPermi="['system:user:super']">修改上级</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="User" @click="handleGoincome(scope.row)"
                          v-hasPermi="['system:incomeLog:list']">收支明细</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="UserFilled" @click="handleTeamDetail(scope.row)"
                          v-hasPermi="['system:incomeLog:list']">团队明细</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button link type="primary" icon="UserFilled" @click="handleTeamTree(scope.row)"
                          v-hasPermi="['system:incomeLog:list']">团队树</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属区域" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属区域"
                check-strictly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否联创">
              <el-radio-group v-model="form.lianchuang">
                <el-radio v-for="dict in lianchuang" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否达人">
              <el-radio-group v-model="form.daren">
                <el-radio v-for="dict in darenArr" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否激励仓分红" label-width="110px">
              <el-radio-group v-model="form.jilicangDivide">
                <el-radio v-for="dict in jilicang" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择" clearable>
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择" clearable>
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="个人等级">
              <el-select v-model="form.levelIds" placeholder="请选择" multiple clearable>
                <el-option v-for="item in levelsUserList" :key="item.levelId" :label="item.levelName"
                  :value="item.levelId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="团队等级">
              <el-select v-model="form.agentLevelId" placeholder="请选择" clearable>
                <el-option v-for="item in levelsUserList1" :key="item.levelId" :label="item.levelName"
                  :value="item.levelId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合伙人等级" label-width="95">
              <el-select v-model="form.hehuorenLevelId" placeholder="请选择" clearable>
                <el-option v-for="item in levelsUserList2" :key="item.levelId" :label="item.levelName"
                  :value="item.levelId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="熵豆达人" label-width="95">
              <el-select v-model="form.shangdouDaren" placeholder="请选择" clearable>
                <el-option v-for="item in levelsUserList3" :key="item.levelId" :label="item.levelName"
                  :value="item.levelId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可兑换次数" label-width="95">
              <el-input v-model="form.exchangeNum" placeholder="请输入可兑换次数" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户货币充值 -->
    <el-dialog title="货币充值" v-model="isMoney" width="400px" append-to-body>
      <el-form ref="moneyFormRef" :model="moneyForm" label-width="80px" :rules="moneyRules">
        <el-form-item label="用户">
          <el-input :value="moneyForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="充值货币">
          <el-select v-model="moneyForm.moneyId" placeholder="请选择">
            <el-option v-for="item in moneyList" :key="item.id" :label="item.moneyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值额度">
          <el-input-number v-model="moneyForm.amount"></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="moneyForm.remark" type="textarea" :rows="2" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMoneyForm">确 定</el-button>
          <el-button @click="isMoney = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户修改上级 -->
    <el-dialog title="修改上级" v-model="isUpdateSuper" width="400px" append-to-body>
      <el-form ref="updateSuperFormRef" :model="updateSuperForm" label-width="80px" :rules="superRules">
        <el-form-item label="用户">
          <el-input :value="updateSuperForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="选择上级">
          <el-select v-model="updateSuperForm.superior" placeholder="请选择" remote filterable
            :remote-method="remoteSuper">
            <el-option v-for="item in superList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUserSuperForm">确 定</el-button>
          <el-button @click="isUpdateSuper = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 团队明细弹出 -->
    <el-dialog title="团队明细" v-model="isTeamDetail" width="80%" append-to-body>
      <el-form ref="teamFormRef" :model="teamDetailForm" label-width="80px" :inline="true">
        <el-form-item label="用户手机号" prop="userName" label-width="100">
          <el-input v-model="teamDetailForm.userName" placeholder="请输入用户手机号" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="用户等级" prop="level">
          <el-select v-model="teamDetailForm.levelId" filterable placeholder="请选择用户等级">
            <el-option v-for="item in levelsList" :key="item.levelId" :label="item.levelName" :value="item.levelId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery_push()">搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery_push">重置</el-button>
        </el-form-item>
        <div style="display: flex; margin: 20px 0">
          <p style="margin: 0 20px">直推数量：{{ push_total }}</p>
          <p style="margin: 0 20px">团队总数：{{ allTeamdata }}</p>
          <p style="margin: 0 20px">团队业绩：{{ allTeamdata2 }}</p>
          <p style="margin: 0 20px">今日团队业绩：{{ allTeamToday }}</p>
        </div>
      </el-form>
      <el-table :data="teamList">
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
        <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="等级" align="center" key="sysUserLevel.title" prop="sysUserLevel.title"
          :show-overflow-tooltip="true">
          <template #default="scope">
            <div>
              <div v-for="item in scope.row.levels" :key="item.id">
                <p>{{ item.levelName }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        <el-table-column label="团队收益" align="center" prop="teamProfit" width="120" />
        <el-table-column label="注册时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="push_total > 0" :total="push_total" v-model:page="teamDetailForm.pageNum"
        v-model:limit="teamDetailForm.pageSize" @pagination="handleTeamDetail" />
    </el-dialog>

    <el-dialog title="收款信息" v-model="collShow" width="400px" append-to-body>
      <el-form ref="collFormRef" :model="collForm" label-width="80px">
        <el-form-item label="收款人">
          <el-input v-model="collForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="收款账户">
          <el-input v-model="collForm.cardNo"></el-input>
        </el-form-item>
        <el-form-item label="开户行">
          <el-input v-model="collForm.openBank"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCollForm">确 定</el-button>
          <el-button @click="collShow = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="团队树" v-model="teamTreeShow" width="90%" append-to-body>
      <div style="height: 600px">
        <vue3-tree-org lazy :data="teamTreeData" :load="teamloadData" :horizontal="teamTreeHorizontal"
          :collapsable="teamCollapsable" :label-style="teamStyle" :node-draggable="true" :scalable="true"
          :props="teamTreeProps">
          <template v-slot="{ node }">
            <div class="tree-org-node__text node-label" @click="teamTreeNodeClick(node)">
              <div style="white-space: nowrap">
                昵称：{{ node.$$data.nickName }}
              </div>
              <div style="white-space: nowrap">
                手机号：{{ node.$$data.userName }}
              </div>
            </div>
          </template>
        </vue3-tree-org>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="teamTreeShow = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { ArrowDown } from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
  userRichRecharge,
  updatesuperior,
  getuserTeamList,
  adminAddBank,
  getAdminBank,
  getUserTree,
} from "@/api/system/user";
import { listLevel } from "@/api/system/level";
import { listRole } from "@/api/system/role";
import { listMoney } from "@/api/money/money";
import { ElLoading } from "element-plus";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);

const lianchuang = ref([
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 0,
  },
]);

const darenArr = ref([
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 0,
  },
]);

const jilicang = ref([
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 0,
  },
]);


const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `区域`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true },
]);

const usermsg = ref("");
const select = ref("");
const usermsgList = ref([
  {
    name: "用户账号",
    id: "userName",
  },
  {
    name: "用户昵称",
    id: "nickName",
  },
  {
    name: "真实姓名",
    id: "realName",
  },
  {
    name: "用户编号",
    id: "userId",
  },
  {
    name: "手机号码",
    id: "phonenumber",
  },
]);

function handleShangdou() {
  proxy.download(
    "system/user/balanceExport",
    {
      ...queryParams.value,
    },
    `shangdou_${new Date().getTime()}.xlsx`
  );
}

/**
 * 团队树相关
 * https://sangtian152.github.io/vue3-tree-org/demo
 */
const teamTreeShow = ref(false);
const teamTreeData = ref({});
const teamTreeHorizontal = ref(false); //是否横向
const teamCollapsable = ref(true); //是否可展开
const teamStyle = ref({
  background: "#3890ff",
  color: "#fff",
});
const teamTreeProps = ref({
  id: "userId",
  pid: "superior",
  isLeaf: "leaf",
});

function handleTeamTree(row) {
  teamTreeData.value = {
    userId: row.userId,
    children: [],
    nickName: row.nickName,
    userName: row.userName,
    leaf: false,
  };
  getUserTree({
    userId: row.userId,
    sign: 1,
  }).then((res) => {
    teamTreeData.value.children = res.data;
    teamTreeShow.value = true;
  });
}

function teamloadData(node, resolve) {
  console.log(node);
  getUserTree({
    userId: node.id,
  }).then((res) => {
    resolve(res.data);
  });
}

async function teamTreeNodeClick(node) {
  try {
    // 提取节点的 label 内容
    const contentToCopy = node.$$data.userName;

    // 将内容复制到剪贴板
    await navigator.clipboard.writeText(contentToCopy);
    proxy.$modal.msgSuccess("已复制节点内容: " + contentToCopy);
  } catch (error) {
    console.error("复制节点内容失败:", error);
    proxy.$modal.msgError("复制节点内容失败");
  }
}

const levelsList = ref([]);
const roleList = ref([]);
const levelsUserList = ref([]);
const levelsUserList1 = ref([]);

const userTypeList = ref([
  {
    label: "管理员",
    value: "00",
  },
  {
    label: "会员用户",
    value: "01",
  },
  {
    label: "商户",
    value: "02",
  },
]);

function handleGoincome(row) {
  router.push({ path: "/system/incomeLog", query: { id: row.userId } });
}

/**
 * 收款逻辑处理
 */

const collShow = ref(false);
const collForm = ref({});

function handleColl(row) {
  getAdminBank({
    userId: row.userId,
  }).then((res) => {
    if (res.data) {
      collForm.value = res.data;
    } else {
      collForm.value = {
        realName: "",
        cardNo: "",
        openBank: "",
        createBy: row.userId,
      };
    }
    collShow.value = true;
  });
}

function submitCollForm() {
  adminAddBank(collForm.value).then((res) => {
    proxy.$modal.msgSuccess("添加成功");
    collShow.value = false;
  });
}

// 货币充值
const isMoney = ref(false);
const moneyForm = ref({});
const moneyList = ref([]);
const moneyRules = ref({
  amount: [{ required: true, message: "请输入充值金额", trigger: "blur" }],
  moneyId: [{ required: true, message: "请选择货币", trigger: "change" }],
});

function handleUserCoin(row) {
  moneyForm.value = {
    userId: row.userId,
    userName: row.userName,
    moneyId: undefined,
    amount: undefined,
    remark: undefined,
  };
  isMoney.value = true;
}

function getMoneyList() {
  listMoney({
    pageNum: 1,
    pageSize: 9999,
  }).then((res) => {
    moneyList.value = res.rows || [];
  });
}

getMoneyList();

function submitMoneyForm() {
  proxy.$refs["moneyFormRef"].validate((valid) => {
    if (valid) {
      userRichRecharge(moneyForm.value).then((res) => {
        proxy.$modal.msgSuccess("充值成功!");
        isMoney.value = false;
        getList();
      });
    }
  });
}

// 修改上级
const isUpdateSuper = ref(false);
const updateSuperForm = ref({});
const superList = ref([]);
const superRules = ref({
  superior: [{ required: true, message: "请选择上级", trigger: "change" }],
});

function updateUserSuper(row) {
  updateSuperForm.value = {
    userName: row.userName,
    userId: row.userId,
    superior: undefined,
  };
  isUpdateSuper.value = true;
}

function remoteSuper(e) {
  listUser({
    userName: e,
  }).then((res) => {
    superList.value = res.rows || [];
  });
}

function submitUserSuperForm() {
  proxy.$refs["updateSuperFormRef"].validate((valid) => {
    if (valid) {
      updatesuperior(updateSuperForm.value).then((res) => {
        proxy.$modal.msgSuccess("上级修改成功!");
        isUpdateSuper.value = false;
        getList();
      });
    }
  });
}

// 团队明细
const isTeamDetail = ref(false); // 弹窗
const teamDetailForm = ref({
  userName: null,
  levelId: null,
  pageNum: 1,
  pageSize: 10,
  superior: null,
}); // 搜索
const push_total = ref(0);
const allTeamdata = ref(0);
const allTeamdata2 = ref(0);
const teamList = ref([]);
const allTeamToday = ref(0);

function handleTeamDetail(row) {
  if (row && row.userId) {
    teamDetailForm.value.superior = row.userId;
  }
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    background: "rgba(0,0,0,.7)",
  });
  getuserTeamList(teamDetailForm.value).then((res) => {
    console.log("团队明细", res);
    allTeamdata.value = res.msg;
    allTeamdata2.value = res.data.teamAmount;
    allTeamToday.value = res.data.todayJoinUserNum;
    teamList.value = res.rows;
    push_total.value = res.total;
    isTeamDetail.value = true;
    loadingInstance.close();
  });
}

function handleQuery_push() {
  teamDetailForm.value.pageNum = 1;
  handleTeamDetail();
}

function resetQuery_push() {
  teamDetailForm.value = {
    userName: null,
    levelId: null,
    pageNum: 1,
    pageSize: 10,
    superior: null,
  };
  proxy.resetForm("teamFormRef");
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    nickName: undefined,
    realName: undefined,
    userId: undefined,
    levelId: undefined,
    roleId: undefined,
    userType: route.query.userType,
    jindouAmount: undefined,
    gongdejinAmount: undefined,
  },
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

function usermsgchange() {
  queryParams.value.userName = "";
  queryParams.value.nickName = "";
  queryParams.value.realName = "";
  queryParams.value.userId = "";
  queryParams.value.phonenumber = "";
  usermsg.value = "";
}

const levelsUserList2 = ref([]);
const levelsUserList3 = ref([]);

function getLevelsList() {
  listLevel({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    levelsList.value = res.rows || [];

    levelsUserList.value = levelsList.value.filter((item) => {
      if (item.levelName == "联创") {
        lianchuang.value[0].value = item.levelId;
      }
      if (item.levelName == "达人") {
        darenArr.value[0].value = item.levelId;
      }
      return item.levelType == 1;
    });

    levelsUserList1.value = levelsList.value.filter((item) => {
      return item.levelType == 2;
    });

    levelsUserList2.value = levelsList.value.filter((item) => {
      return item.levelType == 5;
    });
    levelsUserList3.value = levelsList.value.filter((item) => {
      return item.levelType == 4;
    });
    console.log("levelsUserList3", levelsUserList3.value);
  });
}
getLevelsList();

function getRoleList() {
  listRole({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    roleList.value = res.rows || [];
  });
}
getRoleList();

/** 根据名称筛选区域树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询区域下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      userList.value = res.rows;
      total.value = res.total;
    }
  );
}
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  if (select.value == "userName") {
    queryParams.value.userName = usermsg.value;
  } else if (select.value == "nickName") {
    queryParams.value.nickName = usermsg.value;
  } else if (select.value == "realName") {
    queryParams.value.realName = usermsg.value;
  } else if (select.value == "userId") {
    queryParams.value.userId = usermsg.value;
  } else if (select.value == "phonenumber") {
    queryParams.value.phonenumber = usermsg.value;
  } else {
    console.log("没了");
  }
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  usermsgchange();
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}
/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
}
/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
}
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => { });
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/user/importTemplate",
    {},
    `user_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
    levelIds: [],
    lianchuang: undefined,
    daren: undefined,
    exchangeNum: undefined,
    jilicangDivide: undefined,
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  getUser().then((response) => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.userId || ids.value;
  getUser(userId).then((response) => {
    form.value = response.data;
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    form.value.postIds = response.postIds;
    form.value.roleIds = response.roleIds;
    form.value.levelIds = response.levelIds;

    open.value = true;
    title.value = "修改用户";
    form.password = "";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

getDeptTree();
getList();
</script>

<style lang="scss" scoped></style>
